package util;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.IOException;

public class DatabaseUtil {
    private static HikariDataSource dataSource;
    
    static {
        try {
            initDataSource();
        } catch (IOException e) {
            throw new RuntimeException("初始化数据库连接池失败", e);
        }
    }
    
    private static void initDataSource() throws IOException {
        Properties prop = new Properties();
        try (FileInputStream fis = new FileInputStream("src/data/MySQL.conf")) {
            prop.load(fis);
            
            String ip = prop.getProperty("ip");
            String port = prop.getProperty("port");
            String user = prop.getProperty("user");
            String password = prop.getProperty("password");
            
            HikariConfig config = new HikariConfig();
            config.setJdbcUrl(String.format("jdbc:mysql://%s:%s/music_server?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&autoReconnect=true&failOverReadOnly=false&maxReconnects=10", ip, port));
            config.setUsername(user);
            config.setPassword(password);
            
            config.setMaximumPoolSize(30);
            config.setMinimumIdle(15);
            config.setConnectionTimeout(10000);
            config.setIdleTimeout(300000);
            config.setMaxLifetime(600000);
            
            config.setConnectionTestQuery("SELECT 1");
            config.setValidationTimeout(3000);
            config.setInitializationFailTimeout(-1);
            
            config.setAutoCommit(true);
            config.setConnectionInitSql("SET NAMES utf8mb4");
            config.setLeakDetectionThreshold(60000);
            
            config.addDataSourceProperty("cachePrepStmts", "true");
            config.addDataSourceProperty("prepStmtCacheSize", "250");
            config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
            config.addDataSourceProperty("maintainTimeStats", "false");
            
            config.addDataSourceProperty("useServerPrepStmts", "true");
            config.addDataSourceProperty("rewriteBatchedStatements", "true");
            config.addDataSourceProperty("cacheResultSetMetadata", "true");
            config.addDataSourceProperty("useLocalSessionState", "true");
            config.addDataSourceProperty("elideSetAutoCommits", "true");
            
            dataSource = new HikariDataSource(config);
        }
    }
    
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    
    public static void closeConnection() {
        if (dataSource != null) {
            dataSource.close();
        }
    }
} 